<template>
  <bd-popup
    class="custom"
    popupId="lotteryV3ChestConversion"
    :weights="2.9"
    v-model:show="props.show"
    :style="{
      'background-color': 'transparent',
      overflow: 'initial',
    }"
    zIndex="999996"
    teleport="body"
    :overlay-style="{ background: 'rgba(0, 0, 0, 0.5)' }"
    :close-on-click-overlay="false"
  >
    <!-- 背景光环 -->
    <img class="gh" src="/image/inviteFriends/ferr-gh-icon.svg" />
    <!-- 蝴蝶结 -->
    <img class="hdj" src="/image/inviteFriends/free-hdj-icon.svg" />
    <!-- 容器 -->
    <div class="box">
      <div class="box-box">
        <div class="box-box-box">
          <!-- 标题 -->
          <div class="box-title">
            <!-- 容器背景 -->
            <img class="box-title-bg" src="/image/titlebg-icon.svg" />
            <!-- 标题 -->
            <div class="box-title-value">
              {{
                $t(
                  isShowChest
                    ? "lotteryMoney.hdxybx"
                    : "lotteryMoney.congratulations"
                )
              }}
            </div>
          </div>

          <!-- 宝箱动画 -->
          <div v-if="isShowChest" class="vue3Lottie">
            <Vue3Lottie
              v-if="chest.init && file.chest && chest.animationData"
              class="vue3Lottie-dh"
              :width="vue3LottieW"
              :height="vue3LottieH"
              :animationData="chest.animationData"
              :autoPlay="!chest.pause"
              :pauseAnimation="!chest.pause"
            />
            <div class="vue3Lottie-text">*{{ source.length }}</div>
          </div>

          <!-- 奖励 -->
          <div v-if="!isShowChest" class="box-reward items-center">
            <!-- 描述 -->
            <div class="box-reward-desc">
              {{ $t("lotteryMoney.nhdjl") }}
            </div>
            <!-- BDC奖励 -->
            <img
              v-show="result && result.prizeType == 1"
              class="box-reward-img"
              src="/image/inviteFriends/bdcjl-blue.png"
            />
            <!-- 免费卡-奖励 -->
            <img
              v-show="result && result.prizeType == 3"
              class="box-reward-img"
              src="/image/inviteFriends/mfxzk-blue.png"
            />
            <!-- 0.5 美金额度-奖励 -->
            <img
              v-show="
                result && result.prizeType == 2 && result.prizeAmount == '0.5'
              "
              class="box-reward-img"
              src="/image/inviteFriends/mj0.5-green.png"
            />
            <!-- 1 美金额度-奖励 -->
            <img
              v-show="
                result && result.prizeType == 2 && result.prizeAmount == '1'
              "
              class="box-reward-img"
              src="/image/inviteFriends/mj1-green.png"
            />
            <!-- 2 美金额度-奖励 -->
            <img
              v-show="
                result && result.prizeType == 2 && result.prizeAmount == '2'
              "
              class="box-reward-img"
              src="/image/inviteFriends/mj2-green.png"
            />
            <!-- 5 美金额度-奖励 -->
            <img
              v-show="
                result && result.prizeType == 2 && result.prizeAmount == '5'
              "
              class="box-reward-img"
              src="/image/inviteFriends/mj5-green.png"
            />
            <!-- 100 美金额度-奖励 -->
            <img
              v-show="
                result && result.prizeType == 2 && result.prizeAmount == '100'
              "
              class="box-reward-img"
              src="/image/inviteFriends/mj100-green.png"
            />

            <!-- 数值 -->
            <div v-if="result && result.prizeType == 1" class="box-reward-text">
              +{{ result.prizeAmount }}BDC
            </div>
            <div
              v-else-if="result && result.prizeType == 3"
              class="box-reward-text"
            >
              +{{ result.prizeAmount }} {{ $t("lotteryMoney.freeCard") }}
            </div>
            <div
              v-else-if="result && result.prizeType == 2"
              class="box-reward-text"
            >
              ${{
                $t("lotteryMoney.xxxdhed").replace(
                  "xxx",
                  `${result.prizeAmount}`
                )
              }}
            </div>
          </div>

          <!-- 底部按钮 -->
          <div class="box-footer items-center">
            <div
              v-if="!isAlreadyOpen && result && !!result.hitBonus"
              class="box-footer-btn"
              @click.stop="jumpPage"
            >
              {{ $t("lotteryMoney.oldUpdateBtn") }}
            </div>
            <div v-else class="box-footer-btn" @click.stop="confirm">
              {{ $t(isShowChest ? "lotteryMoney.ljkx" : "common.confirm") }}
            </div>
          </div>
        </div>
      </div>
      <!-- 底部按钮-背景 -->
      <img
        class="box-footer-bg"
        src="/image/lottery-v3/chest-share-footerbg.svg.svg"
      />
    </div>
    <!-- 关闭 -->
    <!-- <img
      class="close"
      src="/image/close-fff-icon.svg"
      @click.stop="closePopup"
    /> -->
  </bd-popup>
</template>
<script setup lang="ts" name="conversionChestPopup">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { openLuckyRewardBatch } from "@/api/lottery";
import { useFetch as http } from "@vueuse/core";
import { useUserStore } from "~~/store/modules/user";
import { useLotteryV3Store } from "~~/store/modules/lottery-v3";
import { useWindowSize } from "@vant/use";

const props = withDefaults(
  defineProps<{
    show: boolean;
    source: any;
  }>(),
  {
    show: false,
    source: [],
  }
);

const emit = defineEmits(["update:show", "confirm", "countdownDone"]);
const { t } = useI18n();

const userStore = useUserStore();
const lotteryStore = useLotteryV3Store();

const file = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
  sharePage: "/invite-friends/v3/invite",
  chest: "/lottie/lottery-v3/invite-friends/data.json",
});
// 是都显示宝箱
const isShowChest = ref(true);
/********************************  动画  ********************************/
const { width } = process.client ? useWindowSize() : { width: ref(320) };
const vue3LottieW = computed(() => {
  return (140 / 393) * width.value;
});

const vue3LottieH = computed(() => {
  return (140 / 393) * width.value;
});

const chest = reactive({
  pause: true,
  init: true,
  animationData: null,
});
// 由于动画无法响应式暂停播放,所以依靠 chest.init 这个字段进行重新渲染
const pause_watch = watch(
  () => chest.pause,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      chest.init = false;
      nextTick(() => {
        chest.init = true;
      });
    }
  }
);
/********************************  点击确认  ********************************/
let retrys = 3; // 重试次数
const result = ref(null); // 开箱结果
const confirm = () => {
  // 开箱
  if (props.source && props.source.length > 0) {
    // 如果不是宝箱,则先展示宝箱动画
    if (!isShowChest.value) {
      chest.pause = true;
      isShowChest.value = true;
      return;
    }

    const p = props.source.pop();
    showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
      "z-index": 9999999,
    });

    openLuckyRewardBatch({
      idList: [p.id],
      // idList: [176],
    }).then((res) => {
      /****** zhjdebudgger *******/
      // res.luckyBoxList = [
      //   {
      //     id: 176,
      //     prizeType: 2,
      //     prizeAmount: "1",
      //     hitBonus: 1,
      //   },
      // ];
      /****** zhjdebudgger *******/
      if (res) {
        result.value = res.luckyBoxList[0];
        // 开始动画
        chest.pause = false;
        // 展示奖品
        setTimeout(() => {
          isShowChest.value = false;
        }, 2000);
      } else {
        retrys--;
        chest.pause = true;
        //
        if (retrys <= 0) {
          showToast({
            message: `${t("common.wlycqcxjr")}`,
            "z-index": 9999999,
          });
          closePopup();
        }
      }
    });
  }
  // 关闭弹窗
  else {
    closePopup();
  }
};

// 关闭弹窗
const closePopup = () => {
  emit("update:show", false);
};

// 是不是第一次开箱
const isAlreadyOpen = ref(false);

onMounted(() => {
  // 1. 加载动画资源
  http(file.chest).then((res) => {
    if (res.data.value) {
      chest.animationData = JSON.parse(res.data.value);
    }
  });
  // 2. 获取缓存
  isAlreadyOpen.value = !!localStorage.getItem(
    `${userStore.$state.sid}-conversionChestPopup-firstOpen`
  );
});

onBeforeUnmount(() => {
  pause_watch && pause_watch();
});

const jumpPage = () => {
  // 插入缓存
  localStorage.setItem(
    `${userStore.$state.sid}-conversionChestPopup-firstOpen`,
    Date.now() + ""
  );
  // 跳转到兑奖页面，进行第一次的引导
  navigateI18nTo({
    path: "/lottery-v3/bdc-to-money",
    query: {
      type: "conversionChestPopup",
    },
  });
};
</script>

<style lang="scss" scoped>
.gh {
  position: absolute;
  top: -92 * 2px;
  width: 100vw;
}
.hdj {
  position: absolute;
  z-index: 10;
  left: 50%;
  transform: translateX(-50%);
  top: -48 * 2px;
}
.box {
  position: relative;
  z-index: 9;
  margin: 0 40 * 2px;
  background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);
  border-radius: 12 * 2px;
  overflow: hidden;
  padding: 4 * 2px 4 * 2px 4 * 2px 4 * 2px;
  &-box {
    background: linear-gradient(0deg, #fff 59.68%, #fff6eb 100%);
    border-radius: 12 * 2px;
    overflow: hidden;
    padding: 4 * 2px 4 * 2px 0 4 * 2px;
    &-box {
      background: linear-gradient(0deg, #fff 59.68%, #fff6eb 100%);
      border-radius: 12 * 2px;
      overflow: hidden;
      padding: 10 * 2px 7 * 2px 0 7 * 2px;
      border: 1px solid #ffefdb;
      position: relative;
    }
  }
  &-title {
    width: 100%;
    height: 30 * 2px;
    position: relative;
    &-bg {
      position: absolute;
      top: 0;
      height: 30 * 2px;
    }
    &-value {
      position: relative;
      z-index: 9;
      height: 30 * 2px;
      line-height: 30 * 2px;
      width: 100%;
      text-align: center;
      font-size: 15 * 2px;
      color: #fff;
      font-weight: 590;
    }
  }

  &-reward {
    height: 140 * 2px;
    margin-bottom: 10 * 2px;
    flex-direction: column;

    &-desc {
      text-align: center;
      font-size: 12 * 2px;
      color: #141924;
      margin-top: 10 * 2px;
      margin-bottom: 10 * 2px;
    }
    &-img {
      height: 78 * 2px;
    }
    &-text {
      font-size: 17 * 2px;
      color: #007bff;
      font-weight: 590;

      padding: 2.5 * 2px 8 * 2px;
      border-radius: 100px;
      border: 1px solid #fff;
      background: #d8ebff;
    }
  }

  &-footer {
    position: relative;
    justify-content: center;
    height: 93 * 2px;

    &-bg {
      position: absolute;
      top: 190 * 2px;
      z-index: 8;
      width: 100%;
      height: 135 * 2px;
      margin-left: -4 * 2px;
    }

    &-btn {
      margin-top: 10 * 2px;
      position: relative;
      z-index: 9;
      border-radius: 100px;
      background: linear-gradient(270deg, #fb7f09 0.03%, #ffb901 99.97%);
      color: #fff;
      font-size: 15 * 2px;
      font-weight: 590;
      text-align: center;
      width: 100%;
      padding: 10 * 2px 12 * 2px;
    }
  }
}

.vue3Lottie {
  position: relative;
  height: 140 * 2px;
  margin-bottom: 10 * 2px;
  &-text {
    position: absolute;
    top: 90 * 2px;
    right: 50 * 2px;

    color: #d5602e;
    font-size: 17 * 2px;
    font-weight: 590;
  }
  &-dh {
    position: relative;
    z-index: 9;
    top: 0 * 2px;
  }
}

.close {
  position: relative;
  z-index: 9;
  bottom: -30 * 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 30 * 2px;
  height: 30 * 2px;
}
</style>
